namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// 1.	Start at Workplace homepage
    /// 2.  Select Activities
    /// 3.	Choose Task from Type drop down list
    /// 4.	Select All tasks view
    /// 5.	Open a task (double click)
    /// 6.	Click Notes tab
    /// 7.	Right click on a note and select delete
    /// 8.	Confirm deletion confirmation
    /// 9.  Click Close button
    /// </summary>
    
    public class DeleteNoteOnTask : CrmWebTest
    {
        public void DeleteNoteOnTask_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
            
			EntityRequest TaskEr = new EntityRequest();
			TaskEr.Type = EntityNames.Tasks;
			TaskEr.ParentID = Guid.NewGuid();
			TaskEr.ReturnAs = EntityNames.Tasks;

			Props.Add(EntityNames.Tasks, new EntityRequest[] { TaskEr });
			er.Props = Props;

			EntityRequest NoteEr = new EntityRequest();
			NoteEr.Type = EntityNames.Notes;
			NoteEr.ParentID = Guid.Empty;
			NoteEr.ReturnAs = EntityNames.Notes;

			Props = new System.Collections.Hashtable();
			Props.Add("objectid", new EntityRequest[] { NoteEr });

			TaskEr.Props = Props;

			System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			annotation = (CRMEntity)Entities[EntityNames.Notes];
			EntityManager.Instance.FreeEntity((CRMEntity)Entities[EntityNames.Tasks]);
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
        }
       
        public void DeleteNoteOnTask_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            // Don't delete the entity till end of test run as it is deleted from crm.
            EntityManager.Instance.DeleteEntity(annotation);
            EntityManager.Instance.FreeEntity(user);
        }

        public DeleteNoteOnTask()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            gridXml1 = GridXmlHelper.TaskPageView(-1, myTasksViewId, null, null, null);
            gridXml2 = GridXmlHelper.TaskPageView(-1, allTasksViewId, null, "4212", "1&#x2C;1");

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(DeleteNoteOnTask_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(DeleteNoteOnTask_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
			this.BeginTransaction("NavActivityHomepage");

            // Get the home page
            workplace_home_activities_aspx hp = new workplace_home_activities_aspx(user);
            yield return (hp);

			this.EndTransaction("NavActivityHomepage");

            this.BeginTransaction("NavMyTasks");
            
			// Choose task from activities drop down menu
            ActivitiesWebService.ActivitiesWebService act = new ActivitiesWebService.ActivitiesWebService();
            WebTestRequest wtr = null;
            try { act.GetQueryList(entityName); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            AppGridWebService.AppGridWebService ag = new AppGridWebService.AppGridWebService();
            wtr = null;
            try { ag.Reset(gridXml1, gridId); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("NavMyTasks");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavAllTasks");

                // Search for all tasks
                ag = new AppGridWebService.AppGridWebService();
                wtr = null;

                try { ag.Reset(gridXml2, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavAllTasks");
            }

            this.BeginTransaction("OpenTask");

            // simulate double clicking of a task
            activities_task_edit_aspx dp = new activities_task_edit_aspx(user);
            dp.id = annotation["objectid"];
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx f = new _forms_FormScript_js_aspx(user);
            f.etc = 4212;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            this.EndTransaction("OpenTask");
            
            this.BeginTransaction("DeleteNoteOnTask");

            _controls_notes_notesdata_aspx notes = new _controls_notes_notesdata_aspx(user);
            notes.id = new Guid(annotation["objectid"]);
            notes.ParentEntity = 4212;
            notes.EnableInlineEdit = true;
            notes.EnableInsert = true;
            yield return (notes);

            _grid_cmds_dlg_delete_aspx dlgDel = new _grid_cmds_dlg_delete_aspx(user);
            dlgDel.iObjType = 5;
            dlgDel.iTotal = 1;
            dlgDel.sIds = annotation["annotationid"];
            yield return (dlgDel);

            _grid_cmds_dlg_delete_aspx delPage2 = new _grid_cmds_dlg_delete_aspx(user);
            rpcInfo = Utils.GenerateWRPCToken(_grid_cmds_dlg_delete_aspx.url, user, tokenKey);
            headerItem = new WebTestRequestHeader();
            headerItem.Name = "CRMWRPCTokenTimeStamp";
            headerItem.Value = rpcInfo.timeStamp.ToString();
            delPage2.Headers.Add(headerItem);
            headerItem = new WebTestRequestHeader();
            headerItem.Name = "CRMWRPCToken";
            headerItem.Value = rpcInfo.token;
            delPage2.Headers.Add(headerItem);
            delPage2.Method = "Post"; 

            delPage2.iObjType = 5;
            delPage2.iTotal = 1;
            delPage2.iIndex = 0;
            delPage2.sSubTypes = null;
            delPage2.sSrcQueueId = null;
            delPage2.sParentId = null;
            delPage2.sCalendarId = null;
            delPage2.iId = annotation["annotationid"];

            StringHttpBody httpBody = new StringHttpBody();
            httpBody.BodyString = "<node />";
            httpBody.ContentType = "text/xml";
            delPage2.Body = httpBody;
            yield return (delPage2);

            notes = new _controls_notes_notesdata_aspx(user);
            notes.id = new Guid(annotation["objectid"]);
            notes.ParentEntity = 4212;
            notes.EnableInlineEdit = true;
            notes.EnableInsert = true;
            yield return (notes);

            this.EndTransaction("DeleteNoteOnTask");
        }

        private string gridXml1;
        private string gridXml2;
        private static string gridId = "crmGrid";
        private static string entityName = "task";
        private CRMEntity user;
        private CRMEntity annotation;
        private string crmServer;
        private string tokenKey;

        private static string myTasksViewId = "6CF285AA-EB20-4277-925A-3E9735411FF0";
        private static string allTasksViewId = "2B5F5A5D-2D23-4FE7-AA58-E77995368AE7";

        private WebTestRequestHeader headerItem;
        private WRPCInfo rpcInfo;
        private string referer; 
    }
}